﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MovieRental.DataInterfaces;
using System.Data.Entity;
using System.Configuration;
using MovieRental.EfRepositoryLibrary.Configuration;

namespace MovieRental.EfRepositoryLibrary
{
    public class EfRepositoryFactory : IRepositoryFactory
    {
        private string _connectionString;
        private bool _dropAlways;

        public EfRepositoryFactory()
        {
            var config = (EfRepositoryConfiguration)ConfigurationManager.GetSection("efRepositoryConfiguration");
            _connectionString = ConfigurationManager.ConnectionStrings[config.ConnectionStringName].ConnectionString;
            _dropAlways = config.DropAlways;
            if (_dropAlways)
                Reconnect();
            else
            {
                var context = new MovieRentalEntitiesContainer(_connectionString);
                if (!context.DatabaseExists())
                    context.CreateDatabase();
                context.Dispose();
            }
        }

        public void Reconnect()
        {
            if (_dropAlways)
            {
                var context = new MovieRentalEntitiesContainer(_connectionString);
                if (context.DatabaseExists())
                    context.DeleteDatabase();
                context.CreateDatabase();
                context.Dispose();
            }                  
        }

        public ICartDiscountRepository GetCartDiscountRepository()
        {
            return new EfCartDiscountRepository(_connectionString);
        }

        public ICustomerRepository GetCustomerRepository()
        {
            return new EfCustomerRepository(_connectionString);
        }

        public IEditionRepository GetEditionRepository()
        {
            return new EfEditionRepository(_connectionString);
        }

        public ILoanCartRepository GetLoanCartRepository()
        {
            return new EfLoanCartRepository(_connectionString);
        }

        public IMediaTypeRepository GetMediaTypeRepository()
        {
            return new EfMediaTypeRepository(_connectionString);
        }

        public IMovieRepository GetMovieRepository()
        {
            return new EfMovieRepository(_connectionString);
        }

        public IPersonalDiscountRepository GetPersonalDiscountRepository()
        {
            return new EfPersonalDiscountRepository(_connectionString);
        }

        public ITemporaryDiscountRepository GetTemporaryDiscountRepository()
        {
            return new EfTemporaryDiscountRepository(_connectionString);
        }
    }
}
